<template>
  <div>
    <el-form
      label-width="60px"
      :rules="AvatarRules"
      :model="account"
      ref="ruleFormRef"
    >
      <el-form-item label="账号" prop="name">
        <el-input v-model="account.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="account.password" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import { reactive } from 'vue'
import { AvatarRules } from '../config/account-config'
import type { FormInstance } from 'element-plus'
import LocalCache from '@/utils/cache'
import { useStore } from 'vuex'

export default defineComponent({
  setup() {
    const account = reactive({
      name: LocalCache.getCache('name') ?? '',
      password: LocalCache.getCache('password') ?? ''
    })
    const store = useStore()

    const ruleFormRef = ref<FormInstance>()

    // eslint-disable-next-line prettier/prettier
    const loginAction = (isKeepPassword: boolean) => {
      ruleFormRef.value?.validate((valid) => {
        if (valid) {
          if (isKeepPassword) {
            LocalCache.setCache('name', account.name)
            LocalCache.setCache('password', account.password)
          } else {
            LocalCache.deleteCache('name')
            LocalCache.deleteCache('password')
          }

          store.dispatch('login/loginNow', { ...account })
        }
      })
    }

    const forgetPa = () => {
      account.password = ''
    }

    return { account, AvatarRules, loginAction, ruleFormRef, forgetPa }
  }
})
</script>

<style scoped></style>
